package cn.zyl.demo.qle.operator;

import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.Operator;

import java.util.Arrays;

/**
 * JoinOperator类说明:如何自定义Operator-实现一个功能超级强大、非常好用的join操作符
 * ------------------------------------------------------
 * <p>QLExpress主要通过子类实现Operator.java提供的以下方法来最简单的操作符定义，然后可以被通过addFunction或者addOperator的方式注入到ExpressRunner中</p>
 * <pre>
 *     //示例代码
 *      ExpressRunner runner = new ExpressRunner();
 *      DefaultContext<String, Object> context = new DefaultContext<>();
 *      //第一种方式
 *      runner.addOperator("join",new JoinOperator());
 *      runner.execute("1 join 2 join 3", context, null, false, false); -> [1, 2, 3]
 *      //第二种方式
 *      runner.replaceOperator("+",new JoinOperator());
 *      runner.execute("1 + 2 + 3", context, null, false, false); -> [1, 2, 3]
 *      //第三种方式
 *      runner.addFunction("join",new JoinOperator());
 *      runner.execute("join(1,2,3)", context, null, false, false); -> [1, 2, 3]
 * </pre>
 * <p>使用Operator的基类OperatorBase.java将获得更强大的能力，基本能够满足所有的要求</p>
 * @author z.y.l
 * @version v1.0
 * @date 2020-08-28
 */
public class JoinOperator extends Operator {
    @Override
    public Object executeInner(Object[] list) throws Exception {
        java.util.List<Object> result = new java.util.ArrayList<>();
        Object obj = list[0];
        if(obj instanceof java.util.List){
            result.addAll((java.util.List<Object>)obj);
        }else{
            result.add(obj);
        }
        result.addAll(Arrays.asList(list).subList(1, list.length));
        return result;
    }

    public static void main(String[] args) throws Exception{
        ExpressRunner runner = new ExpressRunner();
        DefaultContext<String, Object> context = new DefaultContext<>();
        runner.addOperator("join",new JoinOperator());
        Object r = runner.execute("1 join 2 join 3", context, null, false, false);
        System.out.println(r);
    }
}
